package com.baidu.process.chat.parser.sourceHandler.impl;

import com.alibaba.fastjson.JSONObject;
import com.baidu.process.chat.core.action.Actions;
import com.baidu.process.chat.core.web.bean.IMRequestServer;
import com.baidu.process.chat.parser.bean.QueryJsonStr;
import com.baidu.process.chat.parser.sourceHandler.BaseSourceHandler;
import com.baidu.process.config.service.OptAnswerService;
import com.baidu.process.ngd.bean.NGDResBody;
import com.baidu.process.record.bean.DialogueRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.baidu.process.constant.RedisKey.ClarfyKey;

/**
 * @Author:fangyuchao
 * @Description:
 * @Date: Create in 11:52 2022/11/11
 */
@Service
public class ChitChatHandler implements BaseSourceHandler {
    @Autowired
    private OptAnswerService optAnswerService;
    @Value("#{'${ngd.filter.answerActions}'.split(',')}")
    private List<String> answerActions;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Override
    public QueryJsonStr handleQuery(NGDResBody ngdResBody, IMRequestServer imRequestServer, DialogueRecord dialogueRecord) {
        QueryJsonStr queryJsonStr = new QueryJsonStr();
        NGDResBody.NGDQueryData  queryData = ngdResBody.getData();
        String sessionId = queryData.getSessionId();
        //重置澄清次数
        redisTemplate.opsForValue().set(ClarfyKey+sessionId,"0",10, TimeUnit.MINUTES);
        Map<String,Object> answer = queryData.getAnswer();
        String answerText = answer.get("answerText").toString();
        queryJsonStr.setSessionId(queryData.getSessionId());
        String action = actionExract(answerText);
        queryJsonStr.setBot(action);
        queryJsonStr.setSource(queryData.getSource());
        queryJsonStr.setContext(queryData.getContext());
        queryJsonStr.setSource(queryData.getSource());
        return queryJsonStr;
    }

    //提取话术内的指令,去除@@符号
    private String actionExract(String suggestAnswer){
        //默认正常回复
        String action = "0";
        for (String action_1 : answerActions){
            if (suggestAnswer.contains(action_1)){
                action=action_1.replace("@","");
                break;
            }
        }
        return action;
    }
}
